package com.soft.sitegenerator.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.soft.sitegenerator.Component;
import com.soft.sitegenerator.DataBaseComponent;
import com.soft.sitegenerator.business.hibernate.NewsGroup;
import com.soft.sitegenerator.business.hibernate.Post;
import com.soft.sitegenerator.business.hibernate.User;
import com.soft.sitegenerator.exceptions.ObjectNotFoundException;
import com.soft.sitegenerator.form.PostEditForm;

public class PostEditAction extends DispatchAction {

	public ActionForward addPost(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		PostEditForm postEditForm = (PostEditForm) form;

		Component component = new DataBaseComponent();
		User user = (User) component.getBean("usersHib");
		
		// Poner el Id del usuario logueado
		user.setId((Long) request.getSession().getAttribute("USER_LOGIN"));

		try {
			user.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}

		postEditForm.setUser(user);
		postEditForm.setGroups(user.getNewsGroups());

		return mapping.findForward("showAdd");
	}

	public ActionForward savePost(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		PostEditForm postEditForm = (PostEditForm) form;

		Component component = new DataBaseComponent();
		User user = (User) component.getBean("usersHib");

		// Poner el Id del usuario logueado
		user.setId((Long) request.getSession().getAttribute("USER_LOGIN"));

		try {
			user.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}

		NewsGroup group = (NewsGroup) component.getBean("newsgroupsHib");
		group.setId(postEditForm.getIdGroup());

		try {
			group.load();
		} catch (ObjectNotFoundException e) {
			e.printStackTrace();
		}

		Post post = postEditForm.getPost();

		post.setCreationDate(new Date());
		post.setNewsGroup(group);
		post.setUser(user);
		post.save();

		return mapping.findForward("showList");

	}

}
